#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#if 1
#define SERVICE_IP "127.0.0.1"
#else
#define SERVICE_IP "101.33.226.86"
#endif

#define PORT 8848

int sockfd;
pthread_mutex_t sockfd_mutex = PTHREAD_MUTEX_INITIALIZER;

void* recv_msg(void* arg)
{
    char msg[128];
    int ret_val = -1;
    while(1)
    {
        bzero(msg, sizeof(msg));
        ret_val = recv(sockfd, msg, sizeof(msg), 0);
        if(ret_val == 0)
        {
            std::cout << "服务器断开连接" << std::endl;
            break;
        }
        else if(ret_val < 0)
        {
            perror("recv");
            break;
        }
        else
        {
            std::cout << "接收到数据：" << msg << std::endl;
        }
    }
    return NULL;
}

int main(int argc, char const *argv[])
{
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1)
    {
        perror("socket");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr(SERVICE_IP);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);

    int ret_val = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret_val == -1)
    {
        perror("connect");
        close(sockfd);
        return -1;
    }

    pthread_t tid;
    pthread_create(&tid, NULL, recv_msg, NULL);

    char msg[128];
    while(1)
    {
        if(fgets(msg, sizeof(msg), stdin) == NULL)
        {
            perror("fgets");
            break;
        }
        pthread_mutex_lock(&sockfd_mutex);
        ret_val = send(sockfd, msg, strlen(msg), 0);
        pthread_mutex_unlock(&sockfd_mutex);
        if(ret_val < 0)
        {
            perror("send");
            break;
        }
        std::cout << "发送信息" << ret_val << "字节" << std::endl;
    }

    pthread_join(tid, NULL);
    close(sockfd);
    return 0;
}